package com.cip.common.util;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.map.ObjectMapper;

import net.sf.json.JSONArray;

import com.cip.common.Constants;

public class CommonUtil {

	/**
	 * <p>
	 * Constructing parameter using the map
	 * -- Every api call 
	 * </p>
	 * @return requestStr
	 */
	public static String convertMapToUrl(Map<String,Object> convertMap)throws Exception {
		
		String requestUrlStr = "";
		
		for (String key : convertMap.keySet()) {
			
			String value =  "";
			
			if(!isEmptyString(String.valueOf(convertMap.get(key)))){
				try {
					value = URLEncoder.encode(String.valueOf(convertMap.get(key)).trim(), "UTF-8");
				} catch (Exception e) {
					throw new Exception("Problem while converting Map to rest api url string :", e);
				}
			}
			
			requestUrlStr = requestUrlStr+"&"+key+"="+value;
			
		}
		
		return requestUrlStr;
	}
	
	/**
	 * <p>
	 * Check the string is empty or not
	 * </p>
	 * @param s
	 * @return
	 */
	public static boolean isEmptyString(String s) {
		 if ((s == null) || (s.trim().length() == 0)) {
			 return (true);
		 } else {
			 return (false);
		 }
	 }
	
	/**
	 * <p>
	 * 
	 * </p>
	 * @param mobileNnumber
	 * @param messageText
	 * @return
	 * @throws Exception
	 */
	public static String constructUrl(String mobileNnumber,String messageText)throws Exception {
		
		String resStringURL = "";
		
		Map<String,Object> paramMap = new HashMap<String, Object>();
		
		paramMap.put("senderID", "TEST SMS");
		paramMap.put("receipientno", mobileNnumber);
		paramMap.put("dcs", "0");
		paramMap.put("msgtxt",messageText);
		paramMap.put("state", "4");
		
		String paramContent = convertMapToUrl(paramMap);
		
		System.out.println("paramContent========================"+paramContent);
		
		try {
			
			resStringURL = "http://api.mVaayoo.com/mvaayooapi/MessageCompose?user="+Constants.API_UNAME+":"+Constants.API_PWORD+paramContent;
			
			System.out.println("resStyringURL================="+resStringURL);
			
		} catch (Exception e) {
			throw new Exception("Error while form api url: "+e.getMessage(),e);
		}
		return resStringURL;
	}
	
	/**
	 * <p>
	 * Sets the given JSONObject into the response.
	 * </p>
	 * 
	 * @param Object
	 *            - JSONObject - contains grid rows and grid headers as JSON
	 *            ARRAY.
	 * @param response
	 *            - HttpServletResponse
	 * 
	 * @throws IOException
	 *             - when error occurs
	 */
	public static void generateResponseThroughJSON(
			final HttpServletResponse response, final Object json)
			throws IOException {
		response.setContentType("application/x-json");
		response.setHeader("Cache-Control", "no-cache");
		response.getWriter().print(json);
	}
	
	/**
	 * <p>
	 * Generates the given map into the JSONObject and sets it into the
	 * response.
	 * </p>
	 * 
	 * @param map
	 *            - Map Collection - name value pair of response strings
	 * @param response
	 *            - HttpServletResponse
	 * 
	 * @throws IOException
	 *             - when error occurs
	 */
	public static void generateResponseThroughJSON(final Object result,
			final HttpServletResponse response) throws IOException {
		Object json = result;
		/*
		 * if(result instanceof Map){ json = JSONObject.fromObject(result);
		 * }else if(result instanceof Object[]){ json =
		 * JSONArray.fromArray((Object[])result); }
		 */

		response.setContentType("application/x-json");
		response.setHeader("Cache-Control", "no-cache");
		response.getWriter().print(json);
	}
	
	/**
	 * Converts a <code>List</code> of objects to a json array
	 * 
	 * @param objectsToConvert
	 *            Objects that need to be converted into a json array
	 * @return A json array e.g. n[ {"allfieldnames" : [name, value]} ]
	 */
	public static JSONArray generateResponseThroughJSON(
			final List objectsToConvert) {
		JSONArray jsonArray = JSONArray.fromObject(objectsToConvert);
		return jsonArray;
	}
	
	/**
	 * Converts a object to a json array
	 * 
	 * @param objectsToConvert
	 *            Objects that need to be converted into a json array
	 * @return A json array e.g. n[ {"allfieldnames" : [name, value]} ]
	 */
	public static JSONArray generateResponseThroughJSON(
			final Object objectsToConvert) {
		JSONArray jsonArray = JSONArray.fromObject(objectsToConvert);
		return jsonArray;
	}

	public static JSONArray generateResponseByJSON(final Set objectsToConvert) {
		JSONArray jsonArray = JSONArray.fromObject(objectsToConvert);
		return jsonArray;
	}

	/**
	 * Gets the json array using writer add the array as response
	 * 
	 * @param response
	 * @param jsonArray
	 * @throws IOException
	 */
	public static void writeJsonArrayToRequest(HttpServletResponse response,
			JSONArray jsonArray) throws IOException {
		response.setContentType("text/json");
		response.setHeader("Cache-Control", "no-cache");
		response.getWriter().print(jsonArray);
	}

	/**
	 * get the response string and add it in response using writer
	 * 
	 * @param resString
	 * @param response
	 * @throws IOException
	 */
	public static void generateResponseAsText(final String resString,
			final HttpServletResponse response) throws IOException {
		response.setContentType("plain/text");
		response.setHeader("Cache-Control", "no-cache");
		response.getWriter().print(resString);
	}
	
	/**
	 * Grid Related
	 */
	/**
	 * Returns Json String from a list.
	 * @param list
	 * @return
	 */
	public static String getJsonString(List<?> list) throws Exception{
		ObjectMapper mapper = new ObjectMapper();
		String jsonString = Constants.EMPTY_STRING;
		try {
			jsonString = mapper.writeValueAsString(list);
		} catch (Exception e) {
			throw new Exception("Error while generating JSON for the list "+list , e);
		} 
		return jsonString;
	}
	
	/**
	 * Create grid column attributes 
	 * @param fieldNameList
	 * @param index
	 * @param width
	 * @param renderFun
	 * @param textAlign
	 * @param isHidden
	 */
	public static void createFieldNameList(List<Map<String, Object>> fieldNameList, String index, String width, String textAlign, String onRenderEvent, String isHidden){
		Map<String, Object> fieldNameMap = new HashMap<String, Object>();
		fieldNameMap.put("index", index);
		fieldNameMap.put("width", width);
		fieldNameMap.put("textAlign", textAlign);
		fieldNameMap.put("isHidden", isHidden);
		fieldNameMap.put("onRenderEvent", onRenderEvent);
		fieldNameList.add(fieldNameMap);
	}
}
